package utils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;








import param.pub.Publicresponse;
import play.Logger;
import play.mvc.Http.Response;


public class ErrorMailUtil {
	private static String appname = PropertyUtil.getProperty("application.name");
	private static String province = PropertyUtil.getProperty("centre_topic");
	private static String requrl = "http://"+PropertyUtil.getProperty("mail.url")+"/saveerror";
	
	public static void sendMail(String errorcode, Publicresponse response){
		String responsetext = null;
		HttpClient client = new HttpClient();
		List<Header> headers = new ArrayList<Header>();  
        headers.add(new Header("Accept", "application/json, text/javascript, */*; q=0.01"));
        headers.add(new Header("clienttype", "7"));
        client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(6000);
        client.getHttpConnectionManager().getParams().setSoTimeout(6000);
        PostMethod postMethod = null;
    	try {
    		NameValuePair[] params = toPair(errorcode, response);
    		postMethod = new PostMethod(requrl.toString());
			postMethod.addParameters(params);
			int status = client.executeMethod(postMethod);
        	responsetext = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			Logger.log4j.error("发送错误邮件时发生异常", e);
		}finally{
			postMethod.releaseConnection();
		}
	}
	
	public static void sendMail(String errorcode, String errorcontent){
		String responsetext = null;
		HttpClient client = new HttpClient();
		List<Header> headers = new ArrayList<Header>();  
        headers.add(new Header("Accept", "application/json, text/javascript, */*; q=0.01"));
        headers.add(new Header("clienttype", "7"));
        client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(6000);
        client.getHttpConnectionManager().getParams().setSoTimeout(6000);
        PostMethod postMethod = null;
    	try {
    		NameValuePair[] params = toPair(errorcode, errorcontent);
    		postMethod = new PostMethod(requrl.toString());
			postMethod.addParameters(params);
			int status = client.executeMethod(postMethod);
        	responsetext = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			Logger.log4j.error("发送错误邮件时发生异常", e);
		}finally{
			postMethod.releaseConnection();
		}
	}
	
	private static NameValuePair[] toPair(String errorcode, String errorcontent) throws UnsupportedEncodingException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String application = appname;
		if(province != null && province.trim().length()>0){
			application = appname+"_"+province;
		}else{
			application = appname+"_jiangxi";
		}
		String eMessage = errorcontent+new Date().getTime();
		StringBuffer sb = new StringBuffer("");
		StackTraceElement[] eles = Thread.currentThread().getStackTrace();
		sb.append("application:").append(application).append(",").append("class:").append(eles[3].getClassName()).append(",")
		.append("method:").append(eles[3].getMethodName());
		NameValuePair[] pairs = new NameValuePair[7];
		NameValuePair nvp = new NameValuePair("errorLog.errorname",Md5Encrypt.md5(eMessage));
		pairs[0] = nvp;
		nvp = new NameValuePair("errorLog.applicationname","13");
		pairs[1] = nvp;
		nvp = new NameValuePair("errorLog.errorcode",errorcode);
		pairs[2] = nvp;
		nvp = new NameValuePair("errorLog.function","Mail");
		pairs[3] = nvp;
		nvp = new NameValuePair("errorLog.content",new String((sb.toString()+"\r\n错误时间 : "+sdf.format(new Date())+"\r\n"+errorcontent).getBytes("utf-8"),"iso8859-1"));
		pairs[4] = nvp;
		nvp = new NameValuePair("errorLog.priority","4");
		pairs[5] = nvp;
		nvp = new NameValuePair("deviceid","1");
		pairs[6] = nvp;
		return pairs;
	}
	
	private static NameValuePair[] toPair(String errorcode, Publicresponse response) throws UnsupportedEncodingException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String application = appname;
		if(province != null && province.trim().length()>0){
			application = appname+"_"+province;
		}else{
			application = appname+"_jiangxi";
		}
		String eMessage = response.getResultmsg()+new Date().getTime();
		StringBuffer sb = new StringBuffer("");
		StackTraceElement[] eles = Thread.currentThread().getStackTrace();
		sb.append("application:").append(application).append(",").append("class:").append(eles[3].getClassName()).append(",")
		.append("method:").append(eles[3].getMethodName());
		NameValuePair[] pairs = new NameValuePair[7];
		NameValuePair nvp = new NameValuePair("errorLog.errorname",Md5Encrypt.md5(eMessage));
		pairs[0] = nvp;
		nvp = new NameValuePair("errorLog.applicationname","13");
		pairs[1] = nvp;
		nvp = new NameValuePair("errorLog.errorcode",errorcode);
		pairs[2] = nvp;
		nvp = new NameValuePair("errorLog.function","Mail");
		pairs[3] = nvp;
		nvp = new NameValuePair("errorLog.content",new String((sb.toString()+"\r\n错误时间 : "+sdf.format(new Date())+"\r\n"+response.getResultmsg()).getBytes("utf-8"),"iso8859-1"));
		pairs[4] = nvp;
		nvp = new NameValuePair("errorLog.priority","4");
		pairs[5] = nvp;
		nvp = new NameValuePair("deviceid","1");
		pairs[6] = nvp;
		return pairs;
	}
	
	public static void sendMail(String errorcode, Throwable t){
		String responsetext = null;
		HttpClient client = new HttpClient();
		List<Header> headers = new ArrayList<Header>();  
        headers.add(new Header("Accept", "application/json, text/javascript, */*; q=0.01"));
        headers.add(new Header("clienttype", "7"));
        client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(6000);
        client.getHttpConnectionManager().getParams().setSoTimeout(6000);
        PostMethod postMethod = null;
    	try {
    		NameValuePair[] params = toPair(errorcode, t);
    		postMethod = new PostMethod(requrl.toString());
			postMethod.addParameters(params);
			int status = client.executeMethod(postMethod);
        	responsetext = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			Logger.log4j.error("发送错误邮件时发生异常", e);
		}finally{
			postMethod.releaseConnection();
		}
	}
	
	private static NameValuePair[] toPair(String errorcode, Throwable t) throws UnsupportedEncodingException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String application = appname;
		if(province != null && province.trim().length()>0){
			application = appname+"_"+province;
		}else{
			application = appname+"_jiangxi";
		}
		StringWriter sw = new StringWriter();  
		t.printStackTrace(new PrintWriter(sw));
		String content = sw.toString();
		String eMessage = t.getMessage()+new Date().getTime();
		StringBuffer sb = new StringBuffer("");
		StackTraceElement[] eles = Thread.currentThread().getStackTrace();
		sb.append("application:").append(application).append(",").append("class:").append(eles[3].getClassName()).append(",")
		.append("method:").append(eles[3].getMethodName());
		NameValuePair[] pairs = new NameValuePair[7];
		NameValuePair nvp = new NameValuePair("errorLog.errorname",Md5Encrypt.md5(eMessage));
		pairs[0] = nvp;
		nvp = new NameValuePair("errorLog.applicationname","13");
		pairs[1] = nvp;
		nvp = new NameValuePair("errorLog.errorcode",errorcode);
		pairs[2] = nvp;
		nvp = new NameValuePair("errorLog.function","Mail");
		pairs[3] = nvp;
		nvp = new NameValuePair("errorLog.content",new String((sb.toString()+"\r\n错误时间 : "+sdf.format(new Date())+"\r\n"+content).getBytes("utf-8"),"iso8859-1"));
		pairs[4] = nvp;
		nvp = new NameValuePair("errorLog.priority","4");
		pairs[5] = nvp;
		nvp = new NameValuePair("deviceid","1");
		pairs[6] = nvp;
		return pairs;
	}
}
